<template>
  <div class="app-container">
    <div class="query-container">
      <el-form
        v-show="showSearch"
        ref="queryForm"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item :label="$t('samplesItem')" prop="username">
          <el-input
            v-model="queryParams.item_no"
            :placeholder="$t('inputSamplesItem')"
            clearable
            size="small"
            style="width: 160px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="$t('samplesStatus')" prop="name">
          <el-select v-model="queryParams.status" size="small" clearable :placeholder="$t('inputSamplesStatus')">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('samplesMenuCode')" prop="email">
          <el-input
            v-model="queryParams.menu_code"
            :placeholder="$t('inputSamplesMenuCode')"
            clearable
            size="small"
            style="width: 160px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="$t('samplesValidDate')" prop="email">
          <el-date-picker
            v-model="queryParams.valid_date"
            :placeholder="$t('inputSamplesValidDate')"
            type="date"
            size="small"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item :label="$t('samplesInvalidDate')" prop="email">
          <el-date-picker
            v-model="queryParams.invalid_date"
            :placeholder="$t('inputSamplesInvalidDate')"
            type="date"
            size="small"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >{{ $t('search') }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
            $t('reset')
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="tool-container mb8">
      <el-col :span="1.5">
        <el-button
          v-auth="['CREATE']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t('addBtn') }}</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" :columns="columns" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="samplesList" border :height="tableHeight" @sort-change="sortChange">
      <el-table-column
        :label="$t('samplesItem')"
        sortable
        prop="item_no"
        width="150"
      />
      <el-table-column
        :label="$t('samplesStatus')"
        prop="status_desc"
        sortable
        min-width="100"
      />
      <el-table-column
        :label="$t('samplesMenuCode')"
        prop="menu_desc"
        min-width="100"
      />
      <el-table-column
        :label="$t('samplesWarehouse')"
        prop="warehouse"
        min-width="150"
      />
      <el-table-column
        :label="$t('samplesLocation')"
        prop="location"
        min-width="150"
      />
      <el-table-column
        :label="$t('samplesQuantity')"
        prop="quantity"
        min-width="150"
      />
      <el-table-column
        :label="$t('samplesValidDate')"
        prop="valid_date"
        min-width="110"
      />
      <el-table-column
        :label="$t('samplesInvalidDate')"
        prop="invalid_date"
        min-width="110"
      />
      <el-table-column
        :label="$t('samplesNote')"
        prop="note"
        :show-overflow-tooltip="true"
        min-width="200"
      />
      <el-table-column
        v-if="columns[0].visible"
        :label="$t('createdUser')"
        prop="created"
        min-width="120"
      />
      <el-table-column
        v-if="columns[1].visible"
        :label="$t('createdDate')"
        prop="created_date"
        min-width="180"
      />
      <el-table-column
        v-if="columns[2].visible"
        :label="$t('createdProgram')"
        prop="created_program"
        :show-overflow-tooltip="true"
        min-width="200"
      />
      <el-table-column
        v-if="columns[3].visible"
        :label="$t('updatedUser')"
        prop="updated"
        min-width="120"
      />
      <el-table-column
        v-if="columns[4].visible"
        :label="$t('updatedDate')"
        prop="updated_date"
        min-width="180"
      />
      <el-table-column
        v-if="columns[5].visible"
        :label="$t('updatedProgram')"
        prop="updated_program"
        :show-overflow-tooltip="true"
        min-width="200"
      />
      <el-table-column
        :label="$t('operate')"
        align="center"
        width="250"
        fixed="right"
        class-name="fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >{{ $t('detailBtn') }}</el-button>
          <el-button
            v-auth="['UPDATE']"
            :disabled="scope.row.status === 'C'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{ $t('modifyBtn') }}</el-button>
          <el-dropdown
            v-more
            size="mini"
            trigger="click"
            @command="command => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right" />{{ $t('moreBtn') }}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-auth="['RELEASE']"
                :disabled="scope.row.status === 'R' || scope.row.status === 'C'"
                command="handleRelease"
                icon="el-icon-unlock"
              >{{ $t('releaseBtn') }}</el-dropdown-item>
              <el-dropdown-item
                v-auth="['CLOSE']"
                :disabled="scope.row.status === 'O' || scope.row.status === 'C'"
                command="handleClose"
                icon="el-icon-circle-close"
              >{{ $t('closeBtn') }}</el-dropdown-item>
              <el-dropdown-item
                v-auth="['DELETE']"
                :disabled="scope.row.status !== 'O'"
                command="handleDelete"
                icon="el-icon-delete"
              >{{ $t('deleteBtn') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />
    <SamplesSheet ref="samplesSheet" @refreshList="getList" />
    <SamplesInquire ref="samplesInquire" />
  </div>
</template>

<script>
import store from '@/store';
import resizeElTableHeightMixin from '@/mixins/ResizeElTableHeightMixin'
import { mapGetters } from 'vuex';
import { deleteSamplesApi, releaseSamplesApi, closeSamplesApi } from '../api/samples.api';
import { getDropDownCodeTableListApi } from '@/api/common/common'
import SamplesInquire from './SamplesInquire';
import SamplesSheet from './SamplesSheet';

export default {
  name: 'Samples',
  components: {
    SamplesInquire,
    SamplesSheet
  },
  mixins: [resizeElTableHeightMixin],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        item_no: undefined,
        status: undefined,
        menu_code: undefined,
        valid_date: undefined,
        invalid_date: undefined,
        ordering: undefined
      },
      // 显示隐藏列信息
      columns: [
        { key: 0, label: this.$t('createdUser'), visible: false },
        { key: 1, label: this.$t('createdDate'), visible: false },
        { key: 2, label: this.$t('createdProgram'), visible: false },
        { key: 3, label: this.$t('updatedUser'), visible: true },
        { key: 4, label: this.$t('updatedDate'), visible: true },
        { key: 5, label: this.$t('updatedProgram'), visible: false }
      ],
      statusOptions: [],
      // 操作权限控制
      permissions: []
    };
  },
  computed: {
    ...mapGetters(['samplesList'])
  },
  created() {
    /** Vue实例创建之后初始化数据 */
    this.handleOperatePermission();
    this.handleQueryStatusOptions();
    this.getList();
  },
  methods: {
    /** 查询数据列表 */
    async getList() {
      // 查询前启动遮罩层
      this.loading = true;
      // 查询数据
      var resp = await store.dispatch('samples/getSamplesList', this.queryParams);
      if (resp.success) {
        // 接口执行成功，关闭遮罩层
        this.total = resp.data.count;
        this.loading = false;
      } else {
        // 接口执行失败，提示错误信息并关闭遮罩层
        this.targaMessageBox(this, resp.msg);
        this.loading = false;
      }
    },
    /** 获取页面操作权限 */
    handleOperatePermission() {
      // handleMenuPermission为内置方法，可以获取当前页面的操作权限，并返回数组
      this.permissions = this.handleMenuPermission(this);
    },
    /** 获取页面状态初始数据 */
    async handleQueryStatusOptions() {
      var params = { 'model': 'Samples', 'field': 'status' }
      var resp = await getDropDownCodeTableListApi(params)
      if (resp.success) {
        this.statusOptions = resp.data;
      } else {
        this.targaMessageBox(this, resp.msg);
      }
    },
    /** 处理列表排序 */
    sortChange({ prop, order }) {
      // prop：需要排序字段
      // order：排序方式，倒叙还是正序
      var ordering;
      // 重置查询条件中的排序规则：ordering
      if (order === 'ascending') {
        ordering = '' + prop;
      } else if (order === 'descending') {
        ordering = '-' + prop;
      } else {
        ordering = undefined;
      }
      this.queryParams.ordering = ordering;
      // 重新执行查询
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    /** 更多操作触发 */
    handleCommand(command, row) {
      switch (command) {
        case 'handleDelete':
          this.handleDelete(row);
          break;
        case 'handleRelease':
          this.handleRelease(row)
          break;
        case 'handleClose':
          this.handleClose(row)
          break;
        default:
          break;
      }
    },
    /** 点击修改按钮 */
    handleUpdate(row) {
      this.$refs.samplesSheet.openSheetDialog({ ...row });
    },
    /** 点击明细按钮 */
    handleDetail(row) {
      this.$refs.samplesInquire.openSheetDialog(row);
    },
    /** 点击新建按钮 */
    handleAdd() {
      this.$refs.samplesSheet.openSheetDialog(undefined);
    },
    /** 点击删除按钮 */
    handleDelete(row) {
      this.$confirm(
        this.$t('dataDeleteConfirm', {
          title: this.$t('samplesItem'),
          value: row.item_no
        }),
        this.$t('warning'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'), cancelButtonClass: 'btn-cancel-to-right',
          type: 'warning'
        }
      ).then(async() => {
        var resp = await deleteSamplesApi(row.id);
        if (resp.success) {
          this.targaMessage(
            this.$t('deleteSuccess', {
              title: this.$t('samplesItem'),
              value: row.item_no
            })
          );
          this.getList();
        } else {
          this.targaMessageBox(this, resp.msg);
        }
      });
    },
    /** 点击生效按钮 */
    handleRelease(row) {
      this.$confirm(
        this.$t('dataReleaseConfirm', {
          title: this.$t('samplesItem'),
          value: row.item_no
        }),
        this.$t('warning'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'), cancelButtonClass: 'btn-cancel-to-right',
          type: 'warning'
        }
      ).then(async() => {
        var resp = await releaseSamplesApi(row.id);
        if (resp.success) {
          this.targaMessage(
            this.$t('releaseSuccess', {
              title: this.$t('samplesItem'),
              value: row.item_no
            })
          );
          this.getList();
        } else {
          this.targaMessageBox(this, resp.msg);
        }
      });
    },
    /** 点击关闭按钮 */
    handleClose(row) {
      this.$confirm(
        this.$t('dataCloseConfirm', {
          title: this.$t('samplesItem'),
          value: row.item_no
        }),
        this.$t('warning'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'), cancelButtonClass: 'btn-cancel-to-right',
          type: 'warning'
        }
      ).then(async() => {
        var resp = await closeSamplesApi(row.id);
        if (resp.success) {
          this.targaMessage(
            this.$t('closeSuccess', {
              title: this.$t('samplesItem'),
              value: row.item_no
            })
          );
          this.getList();
        } else {
          this.targaMessageBox(this, resp.msg);
        }
      });
    }
  }
};
</script>

